#include "addnewdye.h"
#include "ui_addnewdye.h"

#include <QButtonGroup>
#include <QDebug>
#include <QMessageBox>

AddNewDye::AddNewDye(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddNewDye)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint);

    /* 限制文本框输入限制 */
    /* 染料名称 */
    QRegExp dyeNamerx("(\\w|-){1,50}");
    QRegExpValidator *dyeNameReg = new QRegExpValidator(dyeNamerx, this);
    ui->dyeName->setValidator(dyeNameReg);
    /* 波长 */
    QRegExp waverx("^[1-9][0-9]{0,2}");
    QRegExpValidator *waveReg = new QRegExpValidator(waverx, this);
    ui->dyeWavelength->setValidator(waveReg);

    /* 初始化 */
    DLDB = new DyeLibrary();
    configFileService = new ConfigFileService();
    cusMsg = new CustomMessageBox();

    QButtonGroup *btnGroup = new QButtonGroup();
    btnGroup->addButton(ui->both);
    btnGroup->addButton(ui->reporter);
    btnGroup->addButton(ui->quencher);
    this->newDye.dyeType = ui->both->text();

    ui->dyeName->setPlaceholderText("请输入染料名");
    ui->dyeWavelength->setPlaceholderText("请输入波长(nm)");

    connect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(getDyeType(QAbstractButton*)));
    connect(ui->ok, &QPushButton::clicked, this, &AddNewDye::getNewDyeInfo);
    connect(ui->cancel, &QPushButton::clicked, this, [=](){
        ui->dyeName->clear();
        ui->dyeWavelength->clear();
        ui->both->isChecked();
        this->close();
    });
}

AddNewDye::~AddNewDye()
{
    delete ui;
}

void AddNewDye::getNewDyeInfo(){
    /* 判空 */
    if(ui->dyeName->text() == ""){
        cusMsg->show(this, CMsg::CWarning, "警告", "染料名不能为空！");
        return;
    }
    else if(ui->dyeWavelength->text() == ""){
                cusMsg->show(this, CMsg::CWarning, "警告", "波长(nm)不能为空！");
        return;
    }

    /* 获取所有染料 */
    allDyeInfos = DLDB->show();

    /* 获取配置文件的染料 */
    for(int i = 0; i < configFileService->getDyes().size(); i++){
        allDyeInfos.append(configFileService->getDyes()[i]);
    }

    /* 配置新染料结构体 */
    newDye.dyeName = ui->dyeName->displayText();
    newDye.dyeCreator = "自定义";
    newDye.waveLength = ui->dyeWavelength->displayText();
    newDye.status = "1";

    /* 查重 */
    for(int i = 0; i < allDyeInfos.size(); i++){
        if(allDyeInfos[i]["name"] == newDye.dyeName){
            cusMsg->show(this, CMsg::CInformation, "染料库", "染料名称重复");
            return;
        }
    }

    emit newDyeInfo(newDye);

    allDyeInfos.clear();
    this->close();
    ui->dyeName->clear();
    ui->dyeWavelength->clear();
    ui->both->isChecked();
}

void AddNewDye::getDyeType(QAbstractButton* radioBtn){
    this->newDye.dyeType = radioBtn->text();
}
